.PHONY: all build clean test deps run-daemon run-cli install docker-build

# 变量
BINARY_DAEMON=lvm-daemon
BINARY_CLI=lvm-cli
BUILD_DIR=build
GO=go
GOFLAGS=-v

# 默认目标
all: clean deps fmt build

# 安装依赖
deps:
	@echo "Installing dependencies..."
	$(GO) mod download
	$(GO) mod tidy

# 构建
build: build-daemon build-cli

build-daemon:
	@echo "Building daemon..."
	CGO_ENABLED=1 $(GO) build $(GOFLAGS) -o $(BUILD_DIR)/$(BINARY_DAEMON) ./cmd/lvm-daemon

build-cli:
	@echo "Building CLI..."
	$(GO) build $(GOFLAGS) -o $(BUILD_DIR)/$(BINARY_CLI) ./cmd/lvm-cli

# 运行
run-daemon: build-daemon
	@echo "Running daemon..."
	sudo $(BUILD_DIR)/$(BINARY_DAEMON)

run-cli: build-cli
	@echo "Running CLI..."
	$(BUILD_DIR)/$(BINARY_CLI) $(ARGS)

# 测试
test:
	@echo "Running tests..."
	$(GO) test -v -race -coverprofile=coverage.out ./...

test-coverage: test
	$(GO) tool cover -html=coverage.out

# 代码检查
lint:
	@echo "Running linters..."
	golangci-lint run

# 格式化代码
fmt:
	@echo "Formatting code..."
	$(GO) fmt ./...
# 	goimports -w .

# 安装到系统
install: build
	@echo "Installing binaries..."
	sudo cp $(BUILD_DIR)/$(BINARY_DAEMON) /usr/local/bin/
	sudo cp $(BUILD_DIR)/$(BINARY_CLI) /usr/local/bin/
	@echo "Installed to /usr/local/bin/"

# 清理
clean:
	@echo "Cleaning..."
	rm -rf $(BUILD_DIR)
	rm -f coverage.out

# Docker 构建
docker-build:
	@echo "Building Docker image..."
	docker build -t lvm-manager:latest -f Dockerfile .

# 开发环境
dev-setup:
	@echo "Setting up development environment..."
	@echo "Installing required system packages..."
	@echo "Ubuntu/Debian: sudo apt-get install -y libvirt-dev pkg-config"
	@echo "RHEL/CentOS: sudo yum install -y libvirt-devel"
	@echo "macOS: brew install libvirt"

# 生成 systemd 服务文件
systemd-install: install
	@echo "Installing systemd service..."
	sudo cp configs/lvm-daemon.service /etc/systemd/system/
	sudo systemctl daemon-reload
	@echo "Enable with: sudo systemctl enable lvm-daemon"
	@echo "Start with: sudo systemctl start lvm-daemon"

# 帮助
help:
	@echo "LVM Manager Build System"
	@echo ""
	@echo "Targets:"
	@echo "  all            - Clean, install deps, and build"
	@echo "  build          - Build daemon and CLI"
	@echo "  build-daemon   - Build daemon only"
	@echo "  build-cli      - Build CLI only"
	@echo "  run-daemon     - Run daemon (requires sudo)"
	@echo "  run-cli        - Run CLI with ARGS variable"
	@echo "  test           - Run tests"
	@echo "  test-coverage  - Run tests with coverage report"
	@echo "  lint           - Run linters"
	@echo "  fmt            - Format code"
	@echo "  install        - Install to /usr/local/bin"
	@echo "  clean          - Remove build artifacts"
	@echo "  docker-build   - Build Docker image"
	@echo "  dev-setup      - Show development setup instructions"
	@echo "  help           - Show this help"